package com.yiyihealth.cherriesadmin.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yiyihealth.cherriesadmin.core.http.HttpResult;
import com.yiyihealth.cherriesadmin.core.service.impl.BaseServiceImpl;
import com.yiyihealth.cherriesadmin.mapper.PaPatientinfoMapper;
import com.yiyihealth.cherriesadmin.mapper.PubHospitalMapper;
import com.yiyihealth.cherriesadmin.mapper.PubPatientsMapper;
import com.yiyihealth.cherriesadmin.mapper.PubSuffererMapper;
import com.yiyihealth.cherriesadmin.model.PaPatientinfo;
import com.yiyihealth.cherriesadmin.model.PubHospital;
import com.yiyihealth.cherriesadmin.model.PubPatients;
import com.yiyihealth.cherriesadmin.model.PubSufferer;
import com.yiyihealth.cherriesadmin.model.his.ExecutionResult;
import com.yiyihealth.cherriesadmin.model.his.PaPatientinfoext;
import com.yiyihealth.cherriesadmin.model.wrapper.PubPatientsWrapper;
import com.yiyihealth.cherriesadmin.service.PubPatientsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 患者信息表(PubPatients)表服务实现类
 *
 * @author chen
 * @since 2020-09-14 20:03:30
 */
@Service("pubPatientsService")
public class PubPatientsServiceImpl extends BaseServiceImpl<PubPatients, PubPatientsWrapper, Long> implements PubPatientsService {
    @Resource
    private PubPatientsMapper pubPatientsMapper;
    @Resource
    private PaPatientinfoMapper paPatientinfoMapper;
    @Resource
    private PubHospitalMapper hospitalMapper;
    @Resource
    private PubSuffererMapper suffererMapper;
    private Snowflake snowflake = IdUtil.getSnowflake(1, 1);


    @Autowired
    private void setEntityMapper() {
        super.setEntityMapper(pubPatientsMapper);
    }

    @Override
    public void ExtractHisData() throws Exception {
        String tokenStr = "";
        String url="";
        for (int i = 0; i < 1; i++) {
            String json = JSONUtil.parseObj("{}").toString();
            try {
                tokenStr = HttpUtil.post(url+"/paPatientinfo/select_list", json);
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("第三方接口异常");
            }
            HttpResult httpResult = JSONUtil.toBean(JSONUtil.parseObj(tokenStr),HttpResult.class);
            List<PaPatientinfo> paPatientinfoList = JSONUtil.toList((JSONArray) httpResult.getData(),PaPatientinfo.class);
            for (PaPatientinfo paPatientinfo:paPatientinfoList){
                try {
                    tokenStr = HttpUtil.get(url+"/paPatientinfoext/select_by_primary_key?id="+paPatientinfo.getBinglilh());
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new Exception("第三方接口异常");
                }
                httpResult = JSONUtil.toBean(JSONUtil.parseObj(tokenStr),HttpResult.class);
                PaPatientinfoext paPatientinfoext = JSONUtil.toBean((JSONObject) httpResult.getData(),PaPatientinfoext.class);
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("binglihao",paPatientinfo.getBinglihao());
                paramMap.put("xingming",paPatientinfo.getXingming());
                paramMap.put("jiuzhenkh",paPatientinfo.getJiuzhenkh());
                List<PaPatientinfo> paPatientinfos = paPatientinfoMapper.selectList(paramMap);
                if (!CollectionUtils.isEmpty(paPatientinfos)){
                    continue;
                }
                PubPatients pubPatients = new PubPatients();
                PubSufferer sufferer = new PubSufferer();
                if (Optional.ofNullable(paPatientinfoext).isPresent()){
                    pubPatients = pubPatientsMapper.selectByIDCard(paPatientinfoext.getLianxiff());
                    if (!Optional.ofNullable(pubPatients).isPresent()){
                        pubPatients = createBean(paPatientinfo,pubPatients,url);
                        pubPatientsMapper.insert(pubPatients);
                        sufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                        sufferer.setPatId(pubPatients.getId());
                        sufferer.setPatName(pubPatients.getPatName());
                        sufferer.setPatSex(pubPatients.getPatSex());
                        sufferer.setPatPhone(pubPatients.getPatPhone());
                        sufferer.setPatCardNum(pubPatients.getPatCardNum());
                        suffererMapper.insert(sufferer);
                    }
                }else {
                    pubPatients = pubPatientsMapper.selectByIDCard(paPatientinfoext.getLianxiff());
                    if (!Optional.ofNullable(pubPatients).isPresent()){
                        pubPatients = createBean(paPatientinfo,pubPatients,url);
                        pubPatientsMapper.insert(pubPatients);
                        sufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                        sufferer.setPatId(pubPatients.getId());
                        sufferer.setPatName(pubPatients.getPatName());
                        sufferer.setPatSex(pubPatients.getPatSex());
                        sufferer.setPatPhone(pubPatients.getPatPhone());
                        sufferer.setPatCardNum(pubPatients.getPatCardNum());
                        suffererMapper.insert(sufferer);
                    }
                }
                paPatientinfo.setOpenId(pubPatients.getId());
                paPatientinfoMapper.insert(paPatientinfo);
            }
        }
    }

    @Override
    public PubPatients selectpatientsFuzzyquery(Map<String, Object> map) {
        return pubPatientsMapper.selectpatientsFuzzyquery(map);
    }

    @Override
    public PubPatients insert(PubPatients record) throws Exception {
        pubPatientsMapper.insert(record);
//        PubSufferer sufferer = new PubSufferer();
//        sufferer.setPatIdentityNum(record.getPatIdentityNum());
//        sufferer.setPatId(record.getId());
//        sufferer.setPatName(record.getPatName());
//        sufferer.setPatSex(record.getPatSex());
//        sufferer.setPatPhone(record.getPatPhone());
//        suffererMapper.insert(sufferer);
//        //调用HIS接口注册患者信息数据到HIS
//        ExecutionResult executionResult = storedProcedure(sufferer);
//        if (!executionResult.getOutResult().equals(0)){
//            throw new Exception("executionResult.getOutData()");
//        }
        return record;
    }

    /**
     * 患者信息注册
     * @param sufferer
     * @return
     * @throws Exception
     */
    private ExecutionResult storedProcedure(PubSufferer sufferer) throws Exception {
        //inData=8650696|毛奕能|男|0|330102198411240019|||13738137370||
        Map<String,Object> map = new HashMap<>(7);
        List<PubHospital> hospitalList = hospitalMapper.selectList(map);
        StringBuilder inData =  new StringBuilder();
        //用户编号 varchar2/10 用户在平台的 ID，患者注册到医院时又平台传给医院
        inData.append(sufferer.getId().toString()+"|");
        inData.append(sufferer.getPatName()+"|");
        inData.append(sufferer.getPatSex().equals(1)?"男":"女"+"|");
        inData.append("0|");
        inData.append(sufferer.getPatIdentityNum()+"|");
        inData.append("|");
        inData.append("|");
        inData.append(sufferer.getPatPhone()+"|");
        inData.append("|");
        String tokenStr = "";
        ExecutionResult executionResult = new ExecutionResult();
        for (PubHospital hospital:hospitalList){
            if (Optional.ofNullable(hospital.getHosRegionalCode()).isPresent()){
                try {
                    tokenStr = HttpUtil.post(hospital.getHosRegionalCode()+"/register/storedProcedure", "inData="+inData.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new Exception("第三方接口异常");
                }
                HttpResult httpResult = JSONUtil.toBean(JSONUtil.parseObj(tokenStr),HttpResult.class);
                executionResult = JSONUtil.toBean(JSONUtil.parseObj(httpResult.getData()),ExecutionResult.class);
            }
        }
        return executionResult;
    }

    /**
     * 账户信息修改
     * @param patients
     * @return
     */
    @Override
    public PubPatients modifyPatient(PubPatients patients) throws Exception {
        PubSufferer sufferer = new PubSufferer();

        Map<String,Object> map = new HashMap<>(7);
        map.put("patIdentityNum",patients.getPatIdentityNum());
        map.put("patId",patients.getId());

        List<PubSufferer> pubSuffererList = suffererMapper.selectList(map);
        if (CollectionUtils.isEmpty(pubSuffererList)){
            sufferer.setPatId(patients.getId());
            sufferer.setPatName(patients.getPatName());
            sufferer.setPatIdentityNum(patients.getPatIdentityNum());
            sufferer.setPatPhone(patients.getPatPhone());
            sufferer.setPatSex(patients.getPatSex());
            suffererMapper.insert(sufferer);
        }else {
            sufferer = pubSuffererList.get(0);
            sufferer.setPatName(patients.getPatName());
            sufferer.setPatIdentityNum(patients.getPatIdentityNum());
            sufferer.setPatPhone(patients.getPatPhone());
            sufferer.setPatSex(patients.getPatSex());
            suffererMapper.updateByPrimaryKeySelective(sufferer);
        }

        if (Optional.ofNullable(patients.getId()).isPresent()){
            pubPatientsMapper.updateByPrimaryKeySelective(patients);
        }else {
            pubPatientsMapper.insert(patients);
            patients.setPatCardNum(patients.getId().toString());
            pubPatientsMapper.updateByPrimaryKey(patients);
        }

        //调用HIS接口推送数据到HIS
        ExecutionResult executionResult = storedProcedure(sufferer);
        if (!executionResult.getOutResult().equals(0)){
            throw new Exception(executionResult.getOutData());
        }
        return patients;
    }

    private ExecutionResult modifyDataHIS(PubSufferer sufferer) throws Exception {
        //"inData=14695434|朱绳纬|18757015539"
        //推送预约数据到HIS
        Map<String,Object> map = new HashMap<>(7);
        List<PubHospital> hospitalList = hospitalMapper.selectList(map);
        StringBuilder inData =  new StringBuilder();
        //用户编号 varchar2/10 用户在平台的 ID，患者注册到医院时又平台传给医院
        inData.append(sufferer.getId().toString()+"|");
        inData.append(sufferer.getPatName()+"|");
        inData.append(sufferer.getPatPhone()+"");
        String tokenStr = "";
        ExecutionResult executionResult = new ExecutionResult();
        for (PubHospital hospital:hospitalList){
            if (Optional.ofNullable(hospital.getHosRegionalCode()).isPresent()){
                try {
                    tokenStr = HttpUtil.post(hospital.getHosRegionalCode()+"/modifyName/storedProcedure", "inData="+inData.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new Exception("第三方接口异常");
                }
                HttpResult httpResult = JSONUtil.toBean(JSONUtil.parseObj(tokenStr),HttpResult.class);
                executionResult = JSONUtil.toBean(JSONUtil.parseObj(httpResult.getData()),ExecutionResult.class);
            }
        }
        return executionResult;
    }

    PubPatients createBean(PaPatientinfo paPatientinfo, PubPatients patients,String url) throws Exception {
        patients =  new PubPatients();
        String tokenStr = "";
        String json = JSONUtil.parseObj("{'binglilh':"+paPatientinfo.getBinglilh()+"}").toString();
        try {
            tokenStr = HttpUtil.get(url+"/paPatientinfoext/select_by_primary_key?id="+paPatientinfo.getBinglilh());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("第三方接口异常");
        }
        HttpResult httpResult = JSONUtil.toBean(JSONUtil.parseObj(tokenStr),HttpResult.class);
        PaPatientinfoext paPatientinfoext = JSONUtil.toBean((JSONObject) httpResult.getData(),PaPatientinfoext.class);
        patients.setPatName(paPatientinfo.getXingming());
        patients.setPatCardNum(paPatientinfo.getBinglihao());
        patients.setPatSex(1);
        patients.setPatPhone(paPatientinfo.getLianxiff());
        patients.setPatFamAddress(paPatientinfo.getZhuzhi());
        patients.setPatBirthday(paPatientinfo.getChushengny());
        patients.setPassword(paPatientinfo.getLianxiff());
        patients.setPatIdentityNum(paPatientinfoext.getShenfenzh());
        if (IdcardUtil.isValidCard(paPatientinfoext.getShenfenzh())){
            patients.setPatSex(IdcardUtil.getGenderByIdCard(paPatientinfoext.getShenfenzh()));
        }
        return patients;
    }

}
